package com.jdy.haoduoai.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.SparseArray;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.enums.SelectionMode;
import com.jdy.haoduoai.fragment.CompleteDownloadFragment;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.DownloadItem;
import com.jdy.haoduoai.model.LeMachine;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.socket.SocketThreadManager;
import com.jdy.haoduoai.util.CommonUtil;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.widget.CustomCommonDialog;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

//import com.jdy.haoduoai.R;

//import com.jdy.haoduoai.util.ImHelper;

public class MyDownloadedActivity extends BaseActivity {

  @InjectView(id = R.id.bottomButtons)
  private View mBottomView;
  @InjectView(id = R.id.tv_anim, click = true)
  private TextView tv_story; // 动画
  @InjectView(id = R.id.tv_radio, click = true)
  private TextView tv_radio; // 电台
  @InjectView(id = R.id.completeDownloadedButton)
  private Button mCompleteDownloadBtn;
  @InjectView(id = R.id.uncompleteDownloadedButton)
  private Button mUnCompleteDownloadBtn;
  @SuppressWarnings("unused")
  private DownLoadType mDownLoadType = DownLoadType.DOWNLOADED;
  @SuppressWarnings("unused")
  private StoryType mStoryType = StoryType.STORY;
  @InjectView(id = R.id.viewPager)
  public ViewPager viewPager;
  @InjectView(id = R.id.custor)
  private ImageView custor;
  @InjectView(id = R.id.btn_upright, click = true)
  private Button btn_upright;
  @InjectView(id = R.id.backs, click = true)
  private View imgBtnBack;
  @InjectView(id = R.id.line_layout_type)
  private View line_layout_type;

  private int offset = 0;// 动画图片偏移量
  private int currIndex = 0; // 当前页卡编号

  // private LeSocketManagerService bindService;

  public boolean isBottomVisible;
  public LeUser mLeUser;
  private DownloadPagerAdapter mDownloadPagerAdapter;
  private boolean selectAllButtonState = true;
  private boolean mToastHasShowed = false;

  private enum DownLoadType {
    DOWNLOADED, // 已下载
    UN_FINISHED, // 未完成
  }

  public enum StoryType {
    STORY, // 动画
    RADIO, // 电台
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_downloaded_layout);

    hideTitleView();

    init();
    checkDeviceOnline();
  }

  @Override
  protected void onSaveInstanceState(Bundle outState) {
    // TODO Auto-generated method stub
    // super.onSaveInstanceState(outState);
  }

  private void checkDeviceOnline() {
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (Tools.isNotNullStr(result.data) && result.data.contains("不在线")) {
          toastShow(result.data);
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        if (mLeUser == null) {
          mLeUser = Tools.restoreLeUser();
        }

        int videoId = -1, uid = -1, volume = -1, minutes = -1;

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
        param_.put(HttpUtils.TAG_ACTION_I, "status");
        param_.put(HttpUtils.TAG_OPERATION_I, "control");
      //  param_.put("mode", "im");

        if (videoId != -1) {
          param_.put(HttpUtils.TAG_VIDEO_ID_I, String.valueOf(videoId));
        }
        if (uid != -1) {
          param_.put(HttpUtils.TAG_UID_I, String.valueOf(uid));
        }
        if (volume != -1) {
          param_.put(HttpUtils.TAG_VOLUME, String.valueOf(volume));
        }
        if (minutes != -1) {
          param_.put(HttpUtils.TAG_MINUTE_I, String.valueOf(minutes));
        }
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

        return HttpUtils.startRequest(HttpUtils.API_URL
            + HttpUtils.OPERATE_DEVICE_METHOD_GET, param_,
            HttpUtils.TAG_GET_REQUEST);

      }
    }).execute();

  }

  private void init() {
    offset = Tools.getPixelByDip(this, 65);
    mLeUser = LeXiaoXiaoBanApp.getInstance().getUser();
    isBottomVisible = false;
    mBottomView.setVisibility(View.GONE);

    imgBtnBack.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
    imgBtnBack.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        finish();
      }
    });

    btn_upright.setVisibility(View.VISIBLE);
    btn_upright.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        CompleteDownloadFragment cdFragment = (CompleteDownloadFragment) mDownloadPagerAdapter
            .getFragmentByPosition(viewPager.getCurrentItem());
        isBottomVisible = !isBottomVisible;

        if (isBottomVisible) {
          mBottomView.setVisibility(View.VISIBLE);
          btn_upright.setBackgroundResource(R.drawable.cancle);

          line_layout_type.setVisibility(View.GONE);
        } else {
          mBottomView.setVisibility(View.GONE);
          btn_upright.setBackgroundResource(R.drawable.edit_btn);
          cdFragment.setSelectionMode(SelectionMode.NONE);

          line_layout_type.setVisibility(View.VISIBLE);
        }
        cdFragment.activateSelectMode(isBottomVisible);
      }
    });

    mDownloadPagerAdapter = new DownloadPagerAdapter(
        getSupportFragmentManager());
    viewPager.setAdapter(mDownloadPagerAdapter);

    tv_story.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        viewPager.setCurrentItem(0);
        mStoryType = StoryType.STORY;

        CompleteDownloadFragment cdFragment = (CompleteDownloadFragment) mDownloadPagerAdapter
            .getFragmentByPosition(0);
        cdFragment.setStoryTypeValue(0);
      }
    });

    tv_radio.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        viewPager.setCurrentItem(1);
        mStoryType = StoryType.RADIO;

        CompleteDownloadFragment cdFragment = (CompleteDownloadFragment) mDownloadPagerAdapter
            .getFragmentByPosition(1);
        cdFragment.setStoryTypeValue(1);
      }
    });

    // 已下载
    mCompleteDownloadBtn.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        mDownLoadType = DownLoadType.DOWNLOADED;

        mCompleteDownloadBtn
            .setBackgroundResource(R.drawable.push_tab_left_btn_sel);
        mCompleteDownloadBtn.setTextColor(0xff2bacfc);
        mUnCompleteDownloadBtn
            .setBackgroundResource(R.drawable.push_tab_right_btn);
        mUnCompleteDownloadBtn.setTextColor(0xffffffff);

        viewPager.setCurrentItem(0);
        CompleteDownloadFragment cdFragment = (CompleteDownloadFragment) mDownloadPagerAdapter
            .getFragmentByPosition(0);
        cdFragment.setCompletedFlagValue(true);
        cdFragment.updateCompletedFlagTrigger(true);

        cdFragment = (CompleteDownloadFragment) mDownloadPagerAdapter
            .getFragmentByPosition(1);
        cdFragment.setCompletedFlagValue(true);
      }
    });

    // 未完成
    mUnCompleteDownloadBtn.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        mDownLoadType = DownLoadType.UN_FINISHED;

        mUnCompleteDownloadBtn.requestFocus();
        mUnCompleteDownloadBtn
            .setBackgroundResource(R.drawable.push_tab_right_btn_sel);
        mUnCompleteDownloadBtn.setTextColor(0xff2bacfc);

        mCompleteDownloadBtn.clearFocus();
        mCompleteDownloadBtn
            .setBackgroundResource(R.drawable.push_tab_left_btn);
        mCompleteDownloadBtn.setTextColor(0xffffffff);

        viewPager.setCurrentItem(0);
        CompleteDownloadFragment cdFragment = (CompleteDownloadFragment) mDownloadPagerAdapter
            .getFragmentByPosition(0);
        cdFragment.setCompletedFlagValue(false);
        cdFragment.updateCompletedFlagTrigger(false);

        cdFragment = (CompleteDownloadFragment) mDownloadPagerAdapter
            .getFragmentByPosition(1);
        cdFragment.setCompletedFlagValue(false);
      }
    });

    viewPager.setOnPageChangeListener(new OnPageChangeListener() {
      @Override
      public void onPageScrollStateChanged(int state) {
        if (state == ViewPager.SCROLL_STATE_IDLE) {

        }
      }

      @Override
      public void onPageScrolled(int position, float positionOffset,
          int positionOffsetPixels) {

      }

      @Override
      public void onPageSelected(int position) {
        Animation animation = null;

        switch (position) {
        case 0: {
          if (currIndex == 1) {
            animation = new TranslateAnimation(offset, 0, 0, 0);
          }
          mStoryType = StoryType.STORY;

          CompleteDownloadFragment cdFragment = (CompleteDownloadFragment) mDownloadPagerAdapter
              .getFragmentByPosition(0);
          cdFragment.updateStoryTypeFlagTrigger(0);

          break;
        }
        case 1: {
          if (currIndex == 0) {
            animation = new TranslateAnimation(0, offset, 0, 0);
          }
          mStoryType = StoryType.RADIO;

          CompleteDownloadFragment cdFragment = (CompleteDownloadFragment) mDownloadPagerAdapter
              .getFragmentByPosition(1);
          cdFragment.updateStoryTypeFlagTrigger(1);

          break;
        }
        }

        currIndex = position;

        if (animation != null) {
          animation.setFillAfter(true);
          animation.setDuration(300);
          custor.startAnimation(animation);
        }
      }
    });

    final Button selectButton = (Button) mBottomView
        .findViewById(R.id.selectAllButton);
    selectButton.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {

        selectAllButtonState = !selectAllButtonState;
        CompleteDownloadFragment cdFragment = (CompleteDownloadFragment) mDownloadPagerAdapter
            .getFragmentByPosition(viewPager.getCurrentItem());
        if (!selectAllButtonState) {
          selectButton.setText(getString(R.string.control_button_deselectall));

          cdFragment.activateSelectMode(isBottomVisible);
          cdFragment.setSelectionMode(SelectionMode.SELECT_ALL);
        } else {
          selectButton.setText(getString(R.string.control_button_selectall));
          cdFragment.setSelectionMode(SelectionMode.DESELECT_ALL);
        }
      }
    });

    Button deleteButton = (Button) mBottomView.findViewById(R.id.deleteButton);
    deleteButton.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        CustomCommonDialog.Builder cdb = new CustomCommonDialog.Builder(
            MyDownloadedActivity.this).setTitle("删除提示").setMessage("确定删除吗？")
            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
              }
            }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
                LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
                LeMachine lm = LeXiaoXiaoBanApp.getInstance().getBaby();

                final List<DownloadItem> selectedDownloads = new ArrayList<DownloadItem>();
                final CompleteDownloadFragment cdFragment = (CompleteDownloadFragment) mDownloadPagerAdapter
                    .getFragmentByPosition(viewPager.getCurrentItem());

                SparseBooleanArray checkedItems = cdFragment.getSelectedIds();
                int checkedItemsCount = checkedItems.size();
                for (int i = 0; i < checkedItemsCount; ++i) {
                  int position = checkedItems.keyAt(i);
                  if (checkedItems.valueAt(i)) {
                    selectedDownloads.add(cdFragment.mCompletedDownloadAdapter
                        .getItem(position));
                  }
                }

                String ids = "";
                for (int i = 0; i < selectedDownloads.size(); i++) {
                  final DownloadItem downloadedEpisode = selectedDownloads
                      .get(i);
                  final int episodeId = downloadedEpisode.id;
                  ids += episodeId + ",";
                }

                if (Tools.isNotEmpty(ids)) {
                  ids = ids.substring(0, ids.length() - 1);
                }

                //mImHelper = LeXiaoXiaoBanApp.getInstance().getImHelper();

               // if (mImHelper != null && mImHelper.isLogin()) {
                  try {
                    JSONObject dataJson = new JSONObject();
                    dataJson.put("code", 202);
                    dataJson.put("act", "ctldownload");

                    JSONObject dataJson22 = new JSONObject();
                    dataJson22.put("op", "delete");
                    dataJson22.put("id", ids);

                    dataJson.put("data", dataJson22);
                    SocketThreadManager.getInstance().send(dataJson.toString());
                  } catch (JSONException e) {
                    e.printStackTrace();
                  } catch (Exception e) {
                    e.printStackTrace();
                  }
               // }

                // update ui
                cdFragment.mCompletedDownloadAdapter.getRecordings().removeAll(
                    selectedDownloads);
                cdFragment.mCompletedDownloadAdapter.resetFlag();
                cdFragment.mCompletedDownloadAdapter.notifyDataSetChanged();
                dialog.dismiss();
              }
            });

        if (!isFinishing()) {
          cdb.create().show();
        }
      }
    });

  }

  private class DownloadPagerAdapter extends FragmentPagerAdapter {
    private SparseArray<Fragment> listFragments = new SparseArray<Fragment>();

    public DownloadPagerAdapter(FragmentManager fm) {
      super(fm);
    }

    @Override
    public Fragment getItem(int pos) {
      switch (pos) {
      case 0:
        return CompleteDownloadFragment.newInstance(true, 0,
            MyDownloadedActivity.this);

      case 1:
        return CompleteDownloadFragment.newInstance(true, 1,
            MyDownloadedActivity.this);

      default:
        return null;
      }
    }

    @Override
    public int getCount() {
      return 2;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
      Fragment fragment = (Fragment) super.instantiateItem(container, position);
      listFragments.put(position, fragment);
      return fragment;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
      listFragments.remove(position);
      super.destroyItem(container, position, object);
    }

    public Fragment getFragmentByPosition(int position) {
      return listFragments.get(position);
    }
  }

  @Override
  protected void onDestroy() {

    // unbindService(conn);

    super.onDestroy();
  }
}
